﻿using QuanLyThuVien.Supporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QuanLyThuVien.GUI
{
    public partial class GUIKetNoiCSDL : DevComponents.DotNetBar.Office2007Form
    {
        //----------------------------------------------------------------------
        //Desc: constructor mặc định
        //----------------------------------------------------------------------
        public GUIKetNoiCSDL()
        {
            InitializeComponent();
        }

        //----------------------------------------------------------------------
        //Desc: khởi tạo
        //----------------------------------------------------------------------
        public void HienThiTenCSDL()
        {
            List<string> databaseNames = DatabaseManager.GetAllDatabaseName();
            if (databaseNames != null && databaseNames.Count > 0)
            {
                for (int i = 0; i < databaseNames.Count; i++)
                {
                    try
                    {
                        _cboTenCSDL.Items.Add(databaseNames[i]);
                    }
                    catch { }
                }
            }
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện load form
        //----------------------------------------------------------------------
        private void GUIKetNoiCSDL_Load(object sender, EventArgs e)
        {
            HienThiTenCSDL();
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện click button cancel
        //----------------------------------------------------------------------
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch
            { }
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện click button kết nối
        //----------------------------------------------------------------------
        private void btnKetNoiCSDL_Click(object sender, EventArgs e)
        {
            if (DatabaseManager.MasterConnection == null)
            {
                MessageBox.Show("Chưa kết nối Server");
                return;
            }

            if (_cboTenCSDL.Text == "")
            {
                MessageBox.Show("Chưa chọn tên cơ sở dữ liệu");
                return;
            }

            DatabaseConnection lastDbConnection = null;
            if (DatabaseManager.DbConnection != null && DatabaseManager.DbConnection.Open())
            {
                DatabaseManager.DbConnection.Close();
                lastDbConnection = DatabaseManager.DbConnection;
            }

            string strConn;
            if (DatabaseManager.MasterConnection.UserName != "" && DatabaseManager.MasterConnection.Password != "")
                strConn = DatabaseManager.CreateConnectionString(DatabaseManager.MasterConnection.DataSourceName, _cboTenCSDL.Text
                    , DatabaseManager.MasterConnection.UserName, DatabaseManager.MasterConnection.Password, DatabaseManager.MasterConnection.IntegratedSecurity);
            else
                strConn = DatabaseManager.CreateConnectionString(DatabaseManager.MasterConnection.DataSourceName, _cboTenCSDL.Text
                    , DatabaseManager.MasterConnection.IntegratedSecurity);

            DatabaseManager.DbConnection = new DatabaseConnection(strConn);
            if (DatabaseManager.DbConnection != null && DatabaseManager.DbConnection.Open())
            {
                DatabaseManager.DbConnection.Close();
                MessageBox.Show("Kết nối thành công");
                DatabaseManager.DbConnection.SetContent(DatabaseManager.MasterConnection.DataSourceName, _cboTenCSDL.Text
                    , DatabaseManager.MasterConnection.UserName, DatabaseManager.MasterConnection.Password, DatabaseManager.MasterConnection.IntegratedSecurity);
                this.Close();
            }
            else
            {
                MessageBox.Show("Kết nối thất bại");
                if (lastDbConnection != null)
                    DatabaseManager.DbConnection = lastDbConnection;
            }
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện chọn button load file script
        //----------------------------------------------------------------------
        private void btnLoadFileScript_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "File script (*.sql)|*.sql;";
            dialog.ShowDialog();
            if (dialog.FileName != "")
                _txtScriptFile.Text = dialog.FileName;
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện chọn button TaoMoi
        //----------------------------------------------------------------------
        private void btnTaoMoi_Click(object sender, EventArgs e)
        {
            if (_txtScriptFile.Text == "" || _txtTenCSDLTaoMoi.Text == "")
            {
                MessageBox.Show("Chưa nhập tên cơ sở dữ liệu hoặc đường dẫn");
                return;
            }
            else
            {
                try
                {
                    string[] words = _txtScriptFile.Text.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                    if (words[words.Length - 1].ToLower() != "sql")
                    {
                        MessageBox.Show("Định dạnh không đúng");
                        return;
                    }
                }
                catch { return; }
            }

            if (DatabaseManager.MasterConnection == null)
            {
                MessageBox.Show("Chưa kết nối server");
                return;
            }

            string databaseName = _txtTenCSDLTaoMoi.Text.Trim().ToUpper();
            if (DatabaseManager.CheckDatabaseExist(databaseName) > 0)
            {
                MessageBox.Show("Cơ sở dữ liệu đã tồn tại");
                return;
            }

            FileInfo file = null;
            string script = null;
            try
            {
                file = new FileInfo(_txtScriptFile.Text);
                script = file.OpenText().ReadToEnd();
            }
            catch
            {
                MessageBox.Show("Không đọc được file script");
                return;
            }

            if (DatabaseManager.CreateDatabase(script, databaseName))
            {
                MessageBox.Show("Tạo cơ sở dữ liệu thành công");
                bool existsdatabaseName = false;
                for (int i = 0; i < _cboTenCSDL.Items.Count; i++)
                {
                    if (_cboTenCSDL.Items[i].ToString() == databaseName)
                        existsdatabaseName = true;
                }
                try
                {
                    if (!existsdatabaseName)
                        _cboTenCSDL.Items.Add(databaseName);
                }
                catch { }
                if (_txtTenCSDLTaoMoi.Text != databaseName)
                    _txtTenCSDLTaoMoi.Text = databaseName;
                if (_txtTenCSDLPhucHoi.Text != databaseName)
                    _txtTenCSDLPhucHoi.Text = databaseName;
            }
            else
                MessageBox.Show("Tạo cơ sở dữ liệu thất bại");
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện chọn button load file backup
        //----------------------------------------------------------------------
        private void btnLoadFileBackup_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "File script (*.bak)|*.bak;";
            dialog.ShowDialog();
            if (dialog.FileName != "")
                _txtBackupFile.Text = dialog.FileName;
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện chọn button PhucHoi
        //----------------------------------------------------------------------
        private void btnPhucHoiCSDL_Click(object sender, EventArgs e)
        {
            if (_txtBackupFile.Text == "" || _txtTenCSDLPhucHoi.Text == "")
            {
                MessageBox.Show("Chưa nhập tên cơ sở dữ liệu hoặc đường dẫn");
                return;
            }

            if (DatabaseManager.MasterConnection == null)
            {
                MessageBox.Show("Chưa kết nối server");
                return;
            }

            if (DatabaseManager.RestoreDatabase(_txtBackupFile.Text, _txtTenCSDLPhucHoi.Text))
                MessageBox.Show("Phục hồi dữ liệu thành công");
            else
                MessageBox.Show("Phục hồi dữ liệu thất bại.");
        }

        //----------------------------------------------------------------------
        //Desc: xử lý sự kiện key press
        //----------------------------------------------------------------------
        private void Special_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Utils.IsSpecialKey(e.KeyChar))
                e.Handled = true;
            else
                e.Handled = false;
        }
    }
}
